import {reactive} from 'vue'
import {defineStore} from 'pinia'

const useKnowledgeStore = defineStore('knowledge', () => {
  const knowledgeSelect = reactive({
    id: null,
    name: '',
    knowledge_name: ''
  })

  const storageKey = 'user-select-knowledge-chat'

  const setKnowledge = (id, name) => {
    knowledgeSelect.id = id
    knowledgeSelect.name = name
    localStorage.setItem(storageKey, JSON.stringify({
      id: id,
      name: name
    }))
  }

  const getKnowledge = () => {
    if (knowledgeSelect.id === null) {
      const res = localStorage.getItem(storageKey)
      if (res) {
        try {
          const data = JSON.parse(res)
          setKnowledge(data.id, data.name)
        } catch (e) {
          setKnowledge(0, '')
        }
      } else {
        setKnowledge(0, '')
      }
    }
    return knowledgeSelect
  }

  return {setKnowledge, getKnowledge}
})

export default useKnowledgeStore